package com.jay.lang.clazz;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ProcessCls {
	public static void main(String[] args) throws IOException,
			InterruptedException {

		System.out.println(CmdToolkit.executeCommand(new String[] { "cmd",
				"/c", "cd" }, null, null));

		System.out.println(CmdToolkit.executeCommand(new String[] { "ls" },
				null, null));
		// 设置工作目录
		String[] env = { "JAVA_HOME=C:/Program Files/Java/jdk1.6.0_20",
				"PATH=C:/Program Files/Java/jdk1.6.0_20/bin" };
		// 设置环境变量
		File dir = new File(
				"D:/tools/eclipse-jee-indigo-SR1/workspace/javapkg7");
		// 显示当前Java运行环境信息
		System.out.println(CmdToolkit.executeCommand(new String[] { "cmd",
				"/c", "java", "-version" }, env, dir));
		// 调用当前版本的Java编译器编译源码
		System.out.println(CmdToolkit.executeCommand(new String[] { "cmd",
				"/c", "javac", "ProcessTest1.java" }, env, dir));
	}

	public static final class CmdToolkit {

		private CmdToolkit() {
		}

		public static String executeCommand(String[] cmd, String[] env, File dir)
				throws IOException, InterruptedException {
			Process ps;
			if (dir == null) {
				ps = Runtime.getRuntime().exec(cmd, env);
			} else {
				ps = Runtime.getRuntime().exec(cmd, env, dir);
			}
			Scanner scanner1 = new Scanner(ps.getInputStream());
			Scanner scanner2 = new Scanner(ps.getErrorStream());
			StringBuilder result = new StringBuilder();
			while (scanner1.hasNextLine()) {
				result.append(scanner1.nextLine());
				result.append(System.getProperty("line.separator"));
			}
			while (scanner2.hasNextLine()) {
				result.append(scanner2.nextLine());
				result.append(System.getProperty("line.separator"));
			}
			scanner1.close();
			scanner2.close();
			return result.toString();
		}
	}
}
